"""create_messages_table

Revision ID: 20762b6e8046
Revises: f23a0cec02a7
Create Date: 2025-06-12 17:35:06.920585

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '20762b6e8046'
down_revision: Union[str, None] = 'f23a0cec02a7'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Upgrade schema."""
    # 创建消息类型枚举
    message_type_enum = sa.Enum('USER_TO_ADMIN', 'ADMIN_TO_USER', 'SYSTEM', name='messagetype')
    message_status_enum = sa.Enum('UNREAD', 'READ', 'REPLIED', name='messagestatus')
    
    # 创建枚举类型
    message_type_enum.create(op.get_bind())
    message_status_enum.create(op.get_bind())
    
    # 创建 messages 表
    op.create_table('messages',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('sender_id', sa.Integer(), nullable=False),
        sa.Column('receiver_id', sa.Integer(), nullable=False),
        sa.Column('title', sa.String(length=255), nullable=False),
        sa.Column('content', sa.Text(), nullable=False),
        sa.Column('message_type', message_type_enum, nullable=False),
        sa.Column('status', message_status_enum, nullable=True),
        sa.Column('parent_id', sa.Integer(), nullable=True),
        sa.Column('is_deleted', sa.Boolean(), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('read_at', sa.DateTime(timezone=True), nullable=True),
        sa.ForeignKeyConstraint(['parent_id'], ['messages.id'], ),
        sa.ForeignKeyConstraint(['receiver_id'], ['users.id'], ),
        sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_messages_id'), 'messages', ['id'], unique=False)


def downgrade() -> None:
    """Downgrade schema."""
    op.drop_index(op.f('ix_messages_id'), table_name='messages')
    op.drop_table('messages')
    
    # 删除枚举类型
    sa.Enum(name='messagetype').drop(op.get_bind())
    sa.Enum(name='messagestatus').drop(op.get_bind())
